package com.nxg.pm04;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.LiveFolders;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.nxg.pm04.baseAdpater.AddBaseAdapter;
import com.nxg.pm04.util.URLDTO;

import org.w3c.dom.Text;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * 创建PM视图类
 */
public class CreatePMActivity extends Activity {
    TextView backButton;//返回按钮
    Spinner taskName;//任务名称下拉框
    Spinner assetName;//名称下拉框
    TextView addToList;//添加按钮

    Spinner scheduleModel;//计划模型
    ImageView startDateImg;//开始日期图标
    ImageView endDateImg;//结束日期图标
    EditText startDate;//开始日期
    EditText endDate;//结束日期

    TextView submitButton;//提交按钮
    TextView cancelButton;//取消按钮
    EditText kilometerName;//计划千米
    Calendar calendar;//日历，Calendar就是一个操作日历的工具类
    //列表视图
    ListView listView;
    //List集合 ,用于存资产名称
    List<String> list = new ArrayList<>();
    AddBaseAdapter addBaseAdapter;//添加基本适配器


/*    Date start = null;
    Date end = null;
    int days = 0;*/


    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:{
                    Toast.makeText(CreatePMActivity.this,"submit success",Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_pm);
        //调用getInstance方法来得到对象,保证了每次调用都返回相同的对象。
        calendar = Calendar.getInstance();

        backButton = findViewById(R.id.backButton);
        taskName = findViewById(R.id.taskName);
        assetName = findViewById(R.id.assetNameSpinner);
        addToList = findViewById(R.id.addToListT);
        scheduleModel = findViewById(R.id.scheduleModel);
        startDateImg = findViewById(R.id.startDateImg);
        endDateImg = findViewById(R.id.endDateImg);
        startDate = findViewById(R.id.startDate);
        endDate = findViewById(R.id.endDate);
        submitButton = findViewById(R.id.submitButton);
        cancelButton = findViewById(R.id.cancelButton);
        kilometerName = findViewById(R.id.kilometerName);
        //向添加按钮 ，设置点击监听事件
        addToList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(taskName.getSelectedItem().toString().equals("")||taskName.getSelectedItem().toString().equals("null")){
                    Toast.makeText(CreatePMActivity.this,"任务名称不能为空！",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(assetName.getSelectedItem().equals("") || assetName.getSelectedItem().equals(null)){
                    Toast.makeText(CreatePMActivity.this, "资产不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }

                for (int i = 0; i< list.size() ; i++) {
                    if(list.get(i).toString().equals(assetName.getSelectedItem().toString())){
                        Toast.makeText(CreatePMActivity.this,"同一资产不能重复添加",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                //向列表中添加
                list.add(assetName.getSelectedItem().toString());

                listView = findViewById(R.id.createListPm);
                addBaseAdapter = new AddBaseAdapter(CreatePMActivity.this,list);
                //向列表视图中 设置添加适配
                listView.setAdapter(addBaseAdapter);
            }
        });

        //对开始时间图片 设置点击监听事件
        startDateImg.setOnClickListener(new View.OnClickListener() {
            /**
             *以弹窗方式显示的日期控件叫做DatePickerDialog
             */
            @Override
            public void onClick(View v) {
                new DatePickerDialog(CreatePMActivity.this,new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = String.format("%d-%d-%d",year,month+1,dayOfMonth);
                        startDate.setText(date);
                    }
                },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        //将 结束时间 按钮设置点击监听事件
        endDateImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //以弹窗方式显示的日期控件叫做DatePickerDialog
                new DatePickerDialog(CreatePMActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        //获取日期选择器dp_date设定的年月份
                        // month+1原因是月份是0-11 所有需要加1
                        String date2 = String.format("%d-%d-%d",year,month+1,dayOfMonth);
                        //向该文本中设置日期
                        endDate.setText(date2);
                    }
                },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        taskName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               list = new ArrayList<>();
               listView = findViewById(R.id.createListPm);
                addBaseAdapter = new AddBaseAdapter(CreatePMActivity.this,list);
                listView.setAdapter(addBaseAdapter);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        scheduleModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(scheduleModel.getSelectedItem().toString().equals("Every X Kilometer")){
                    kilometerName.setVisibility(View.VISIBLE);
                    //startDateImage.setOnTouchListener(onTouch());
                    startDate.setText("");
                    endDate.setText("");
                    //开始按钮日期图标 隐藏 不可见，但是它原来占用的位子还在
                    //startDateImg.setVisibility(View.INVISIBLE);
                    //endDateImg.setVisibility(View.INVISIBLE);
                    //开始日期输入框 禁用
                    //startDate.setEnabled(false);
                    //endDate.setEnabled(false);

                    startDateImg.setVisibility(View.GONE);
                    endDateImg.setVisibility(View.GONE);
                    startDate.setVisibility(View.GONE);
                    endDate.setVisibility(View.GONE);


                }else {
                    kilometerName.setVisibility(View.GONE);
                    /*startDate.setEnabled(true);
                    endDate.setEnabled(true);
                    startDateImg.setVisibility(View.VISIBLE);
                    endDateImg.setVisibility(View.VISIBLE);*/
                    startDateImg.setVisibility(View.VISIBLE);
                    endDateImg.setVisibility(View.VISIBLE);
                    startDate.setVisibility(View.VISIBLE);
                    endDate.setVisibility(View.VISIBLE);

                }
            }
             @Override
             public void onNothingSelected(AdapterView<?> parent) {

             }
        });


            //将提交按钮 设置点击监听事件
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSubmitInfo();
                try{

                    //计划模式， 以年，以月，以周
                    if(scheduleModel.getSelectedItem().toString().equals("Every X Kilometer")){
                        startDate.setText("");
                        endDate.setText("");
                        if(kilometerName.getText().toString().equals(" ") || kilometerName.getText().toString().equals("")){
                            Toast.makeText(CreatePMActivity.this, "计划里程不能为空", Toast.LENGTH_SHORT).show();
                            return ;
                        }
                        String kmStr = kilometerName.getText().toString().trim();
                        Log.d(TAG, "onClick: km="+kmStr+"----------");

                        for (int i = 0; i < list.size(); i++) {
                            URLDTO.insertPM(list.get(i).toString(),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),"",kilometerName.getText().toString(),handler);

                        }

                    }else {
                        if(startDate.getText().toString().equals("") || startDate.getText().toString().equals(null)){
                            Toast.makeText(CreatePMActivity.this, "开始日期不能为空", Toast.LENGTH_SHORT).show();
                            return ;
                        }
                        if(endDate.getText().toString().equals("") || endDate.getText().toString().equals(null)){
                            Toast.makeText(CreatePMActivity.this, "结束日期不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }


                        try {
                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                            Date start1 = sdf2.parse(startDate.getText().toString());
                            Date end1 = sdf2.parse(endDate.getText().toString());
                            if(start1.getTime() > end1.getTime()){
                                Toast.makeText(CreatePMActivity.this, "开始日期不能早于结束日期", Toast.LENGTH_SHORT).show();
                                return;
                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        //show();
                       //处理日期格式
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        //将字符串转换为日期格式
                        Date start = sdf.parse(startDate.getText().toString());
                        //结束
                        Date end = sdf.parse(endDate.getText().toString());
                        //时间相减 的值 是毫秒
                        //时间差 = 结束日期 - 开始日期
                        long timeDiff = end.getTime() - start.getTime();
                        //将时间差 取整
                        int days = (int)timeDiff/(24*60*60*1000);
                        //-GregorianCalendar类的setTimeZone方法设置
                        // 你需要的时区IdstartTime1 .setTimeZone(TimeZone.getTimeZone(event.getTimeZoneId()));
                        calendar = new GregorianCalendar();
                        calendar.setTime(start);
                        //showSubmitTimeInfo();
                        //以月为单位
                        if(scheduleModel.getSelectedItem().toString().equals("Monthly")){
                            if(days < 30){
                                Toast.makeText(CreatePMActivity.this, "开始日期与结束日期应大于30天", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            //如果scheduleModel  下拉框选择的是 月份，则执行成功，否则，不能继续执行
                            if(days>=30){
                                int n = (int)days/30;
                                for (int i = 0; i < list.size(); i++) {
                                    for (int j = 0; j <= n; j++) {
                                        calendar.add(calendar.DATE,j*31);
                                        String dd = sdf.format(calendar.getTime());
                                        //设置为开始日期
                                        calendar.setTime(start);
                                        URLDTO.insertPM(list.get(i),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),dd,"0",handler);
                                    }
                                }
                            }else {
                                for (int i = 0; i < list.size(); i++) {
                                    String dd = sdf.format(start);
                                    URLDTO.insertPM(list.get(i),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),dd,"0",handler);
                                }
                            }
                        }else if(scheduleModel.getSelectedItem().toString().equals("Weekly")) {
                            //Toast.makeText(CreatePMActivity.this, "天数："+days, Toast.LENGTH_SHORT).show();
                            if(days < 7){
                                Toast.makeText(CreatePMActivity.this, "开始日期与结束日期应大于7天", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            //以周计算
                            if(days>=7){
                                int n =(int)days/7;
                                for (int i = 0; i < list.size(); i++) {
                                    for (int j = 0; j <= n; j++) {
                                        calendar.add(calendar.DATE,j*8);
                                        String dd = sdf.format(calendar.getTime());
                                        calendar.setTime(start);
                                        URLDTO.insertPM(list.get(i),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),dd,"0",handler);
                                    }
                                }
                            }else {
                                for (int i = 0; i < list.size(); i++) {
                                    String dd  = sdf.format(start);
                                    URLDTO.insertPM(list.get(i),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),dd,"0",handler);
                                }
                            }
                        }else {
                           if(days< 1){
                                Toast.makeText(CreatePMActivity.this, "开始日期与结束日期应大于1天", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            //以天计算
                            if(days>=1){
                                for (int i = 0; i < list.size(); i++) {
                                    for (int j = 0; j <= days; j++) {
                                        calendar.add(calendar.DATE,j*1);
                                        String dd = sdf.format(calendar.getTime());
                                        calendar.setTime(start);
                                        URLDTO.insertPM(list.get(i),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),dd,"0",handler);
                                    }
                                }
                            }else {
                                for (int i = 0; i < list.size(); i++) {
                                    String dd = sdf.format(start);
                                    URLDTO.insertPM(list.get(i),taskName.getSelectedItem().toString(),scheduleModel.getSelectedItem().toString(),dd,"0",handler);
                                }
                            }
                        }

                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        //返回按钮的监听事件
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //设置取消按钮的点击监听事件，
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

     private void showSubmitInfo(){
        if(taskName.getSelectedItem().equals("") || taskName.getSelectedItem().equals(null)){
            Toast.makeText(CreatePMActivity.this, "任务名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
         if(assetName.getSelectedItem().toString().equals("") || assetName.getSelectedItem().toString().equals("null")){
             Toast.makeText(CreatePMActivity.this,"assetName不能为空",Toast.LENGTH_SHORT).show();
             return;
         }
        if(list.size()<=0){
            Toast.makeText(CreatePMActivity.this, "提交的资产不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(scheduleModel.getSelectedItem().equals("") || scheduleModel.getSelectedItem().equals(null)){
            Toast.makeText(CreatePMActivity.this, "计划类型不能为空", Toast.LENGTH_SHORT).show();
        }
    }

/*    private  void show() throws ParseException {
        //处理日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //将字符串转换为日期格式
         start = sdf.parse(startDate.getText().toString());
        //结束
         end = sdf.parse(endDate.getText().toString());
        //时间相减 的值 是毫秒
        //时间差 = 结束日期 - 开始日期
        long timeDiff = end.getTime() - start.getTime();
        //将时间差 取整
         days = (int)timeDiff/(24*60*60*1000);
        //-GregorianCalendar类的setTimeZone方法设置
        // 你需要的时区IdstartTime1 .setTimeZone(TimeZone.getTimeZone(event.getTimeZoneId()));
        calendar = new GregorianCalendar();
        calendar.setTime(start);
    }*/
    /*private void showSubmitTimeInfo() throws ParseException {
        //处理日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //将字符串转换为日期格式
        Date start = sdf.parse(startDate.getText().toString());
        //结束
        Date end = sdf.parse(endDate.getText().toString());
        //时间相减 的值 是毫秒
        //时间差 = 结束日期 - 开始日期
        long timeDiff = end.getTime() - start.getTime();
        //将时间差 取整
        int days = (int) timeDiff / (60 * 60 * 60 * 1000);
        if (scheduleModel.getSelectedItem().toString().equals("Monthly")) {
            if (days < 30) {
                Toast.makeText(CreatePMActivity.this, "开始日期与结束日期应大于30天", Toast.LENGTH_SHORT).show();
                return;
            }
        }else if (scheduleModel.getSelectedItem().toString().equals("Monthly")) {
            if (days < 7) {
                Toast.makeText(CreatePMActivity.this, "开始日期与结束日期应大于7天", Toast.LENGTH_SHORT).show();
                return;
            }
        }else if (scheduleModel.getSelectedItem().toString().equals("Monthly")) {
            if (days < 1) {
                Toast.makeText(CreatePMActivity.this, "开始日期与结束日期应大于1天", Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }
*/
}